﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using ZhimeiSoft.Framework.Client.Base;
using ZhimeiSoft.CharmManager.DOL;
using ZhimeiSoft.Framework.Client.Utils;
using ZhimeiSoft.CharmManager.Client.Manager;
using ZhimeiSoft.CharmManager.Client.Interface;


namespace ZhimeiSoft.CharmManager.Client.Forms
{
    public partial class frmAdjustReservation : FormBase
    {
        private DBEntityReservation reservationInfo = new DBEntityReservation();
        private DBEntityCustomInfo customInfo = new DBEntityCustomInfo();
        private DataTable dtReservation = new DataTable();
        private DataTable dtReservationServiceItem = new DataTable();
        private DataSet dsEmployee = new DataSet();
        private SortedList<int, string> srotEmployeeName = new SortedList<int, string>();
        private bool isDialogResult = false;

        public frmAdjustReservation(DBEntityReservation reservation)
        {
            InitializeComponent();
            reservationInfo = reservation;
            
            cbxRState.Items.Add("预约完成");
            cbxRState.Items.Add("预约过期");
            cbxRState.Items.Add("预约进行中");
            if (reservation.RSTATE == DBEntityReservation.ENUM_RSTATE.C0A)
            {
                //已经预约完成的是不能够进行调整只能查看
                MsgBox.MsgInfo("当前预约已经预约完成，只能进行查看不能够进行调整。");
                btnSave.Enabled = false;
            }
        }

        private void frmAdjustReservation_Shown(object sender, EventArgs e)
        {
            //1、装载预约信息
            //2、双击某条记录可以进行修改，并按照状态进行保存
            //3、点击保存后进行检查直接提交到数据库
            //dsReservation table[0] 表示预约项目  table[1]预约项目主表
            string error = "";
            DataSet dsReservation = new DataSet();
            if (!BussinessProxyManager.Instance.QueryReservationServiceItem(reservationInfo.RESERVATIONID, out dsReservation, out error))
            {
                MsgBox.MsgInfo("获取预约信息错误：" + error);
                return;
            }
            dtReservation = dsReservation.Tables[1].Copy();
            dtReservationServiceItem = dsReservation.Tables[0].Copy();
            //reservationInfo = new DBEntityReservation(dtReservation.Rows[0]);
            DataSet dsCustomInfo;
            if (!BussinessProxyManager.Instance.QueryCustomerID(reservationInfo.CUSTOMERID, out dsCustomInfo, out error))
            {
                MsgBox.MsgInfo("获取用户信息错误：" + error);
                return;
            }
            string customServiceReservationID = string.Empty;
            foreach (DataRow dr in dtReservationServiceItem.Rows)
            {
                customServiceReservationID += ((customServiceReservationID == string.Empty) ? "" : ",") + dr[DBEntityCustomerServiceItemReservationTime.FieldName.CUSTOMERSERVICEITEMID].ToString();
            }
            string sfilter = DBEntityCustomerServiceItemReservationTime.FieldName.CUSTOMERSERVICEITEMID + " IN ( " + customServiceReservationID + ") ";
            if (customServiceReservationID == string.Empty)
            {
                sfilter = " 1 = 2 ";
            }

            DataSet dsCustSvrItemReservationTime = new DataSet();
            if (!BussinessProxyManager.Instance.QueryCustomerServiceItemReservationTime(sfilter, out dsCustSvrItemReservationTime, out error))
            {
                MsgBox.MsgInfo("获取用户会员预约时间表错误：" + error);
                return;
            }

            if (!BussinessProxyManager.Instance.QueryEmployeeState(DBEntityEmployee.ENUM_ESTATE.F0E, out dsEmployee, out error))
            {
                MsgBox.MsgInfo("初始化员工信息错误：" + error);
                return;
            }
            string employeeItem = string.Empty;
            dsEmployee.Tables[0].Columns.Add(new DataColumn("CODEEMPLOYEE", typeof(string)));
            cbxEmployee.Items.Add("不调整");
            foreach (DataRow drEmployee in dsEmployee.Tables[0].Rows)
            {
                srotEmployeeName.Add(Convert.ToInt32(drEmployee[DBEntityEmployee.FieldName.EMPLOYEEID]), drEmployee[DBEntityEmployee.FieldName.ENAME].ToString());
                employeeItem = "[" + drEmployee[DBEntityEmployee.FieldName.ECODE].ToString() + "]" + drEmployee[DBEntityEmployee.FieldName.ENAME].ToString();
                cbxEmployee.Items.Add(employeeItem);
                drEmployee["CODEEMPLOYEE"] = employeeItem;

            }
            int employeeid = -1; 
            if (dtReservationServiceItem.Rows.Count > 1)
            {
                //初始化cbxEmployee
                foreach (DataRow dr in dtReservationServiceItem.Rows)
                {
                    if (employeeid == -1)
                    {
                        employeeid = Convert.ToInt16(dr[DBEntityReservationServiceItem.FieldName.EMPLOYEEID]);
                    }
                    else
                    {
                        if (employeeid != Convert.ToInt16(dr[DBEntityReservationServiceItem.FieldName.EMPLOYEEID]))
                        {
                            employeeid = -1;
                            break;
                        }
                    }
                }
            }
            else
            {
                employeeid = Convert.ToInt16(dtReservationServiceItem.Rows[0][DBEntityEmployee.FieldName.EMPLOYEEID]);
            }
            if (employeeid != -1)
            {
                DataRow[] drEmplyee = dsEmployee.Tables[0].Select(DBEntityReservationServiceItem.FieldName.EMPLOYEEID + " = " + employeeid.ToString());
                if (drEmplyee.Length != 0)
                {
                    int idx = cbxEmployee.Items.IndexOf(drEmplyee[0]["CODEEMPLOYEE"].ToString());
                    if (idx != -1)
                    {
                        cbxEmployee.SelectedIndex = idx;
                    }
                }
            }
            else
            {
                cbxEmployee.SelectedItem = "不调整";
            }
            customInfo = new DBEntityCustomInfo(dsCustomInfo.Tables[0].Rows[0]);
            txtCustomName.Text = dsCustomInfo.Tables[0].Rows[0][DBEntityCustomInfo.FieldName.CNAME].ToString();
            txtCustomNickName.Text = dsCustomInfo.Tables[0].Rows[0][DBEntityCustomInfo.FieldName.CNICKNAME].ToString();
            txtCustomPhone.Text = dsCustomInfo.Tables[0].Rows[0][DBEntityCustomInfo.FieldName.CMOBILEPHONE].ToString();
            //预约到店时间
            DateTime dtimeResevationTime = Convert.ToDateTime(dtReservation.Rows[0][DBEntityReservation.FieldName.RESERVATIONTIME]);
            //预约状态
            cbxRState.Text = DBEntityReservation.ENUM_RSTATE.EnumStrToChineseStr(dtReservation.Rows[0][DBEntityReservation.FieldName.RSTATE].ToString());
            //
            memRMemo.Text = dtReservation.Rows[0][DBEntityReservation.FieldName.RMEMO].ToString();

            reservationDateTime.Value = reservationInfo.RESERVATIONTIME;
            reservationHourTime.CurrDateTime = reservationInfo.RESERVATIONTIME;
            //reservationInfo
            gridReservation.DataSource = dtReservationServiceItem;
        }

        private void cavReservation_DoubleClick(object sender, EventArgs e)
        {
            string error = string.Empty;
            if (cavReservation.FocusedRowHandle < 0)
            {
                return;
            }
            DataRow drReservationInfo = cavReservation.GetDataRow(cavReservation.FocusedRowHandle);
            frmAdjustReservationServiceItem adjustServiceItem = new frmAdjustReservationServiceItem(drReservationInfo, reservationInfo, customInfo);
            if (adjustServiceItem.ShowDialog() != DialogResult.OK)
            {
                return;
            }
            if (btnSave.Enabled == false)
            {
                //只读
                return;
            }
            //调整预约项目
            if (!BussinessProxyManager.Instance.AdjustReservationCustomServiceItem(reservationInfo.RESERVATIONID, adjustServiceItem.AdjustDateTime,
                Convert.ToInt16(drReservationInfo[DBEntityCustomerServiceItem.FieldName.CUSTOMERSERVICEITEMID]), customInfo.CUSTOMERID, out error))
            {
                MsgBox.MsgInfo("调整项目时错误：" + error);
                return;
            }
                        
            //刷新数据
            DataSet dsReservation = new DataSet();
            if (!BussinessProxyManager.Instance.QueryReservationServiceItem(reservationInfo.RESERVATIONID, out dsReservation, out error))
            {
                MsgBox.MsgInfo("获取预约信息错误：" + error);
                return;
            }
            if (dsReservation.Tables[0].Rows.Count == 0)
            {
                MsgBox.MsgInfo("调整完毕。");
                this.DialogResult = DialogResult.OK;
                return;
            }
            isDialogResult = true;
            dtReservation = dsReservation.Tables[1].Copy();
            dtReservationServiceItem = dsReservation.Tables[0].Copy();
            gridReservation.DataSource = dtReservationServiceItem;

        }


        private void cavReservation_CustomDrawCardFieldValue(object sender, DevExpress.XtraGrid.Views.Base.RowCellCustomDrawEventArgs e)
        {
            Rectangle r = e.Bounds;
            string dispTxt = string.Empty;
            if (e.Column.FieldName.Equals(DBEntityReservationServiceItem.FieldName.RESERVATIONSTATE))
            {
                dispTxt = DBEntityReservationServiceItem.ENUM_RESERVATIONSTATE.EnumStrToChineseStr(e.CellValue.ToString());
                e.Style.DrawString(e.Graphics, dispTxt, r);
                e.Handled = true;
            }
            else if (e.Column.FieldName.Equals(DBEntityEmployee.FieldName.EMPLOYEEID))
            {
                dispTxt = srotEmployeeName[Convert.ToInt32(e.CellValue)].ToString();
                e.Style.DrawString(e.Graphics, dispTxt, r);
                e.Handled = true;
            }
        }

        private void buttonX3_Click(object sender, EventArgs e)
        {
            frmCustomReservationMonth frmCustom = new frmCustomReservationMonth();
            frmCustom.QueryReservation(reservationInfo.RESERVATIONTIME, customInfo);
            frmCustom.ShowDialog();
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (!MsgBox.MsgOkCacel("确定要进行预约调整吗？"))
            {
                return;
            }
            int employee = -1;
            if (cbxEmployee.SelectedItem == null)
            {
                MsgBox.MsgInfo("请选择员工。");
                return;
            }
            if (!cbxEmployee.SelectedItem.ToString().Equals("不调整"))
            {
                DataRow[] drEmployee = dsEmployee.Tables[0].Select("CODEEMPLOYEE = '" + cbxEmployee.SelectedItem.ToString() + "'");
                employee = Convert.ToInt16(drEmployee[0][DBEntityEmployee.FieldName.EMPLOYEEID]);
            }
            string error = string.Empty;
            reservationInfo.RESERVATIONTIME = new DateTime(reservationDateTime.Value.Year, reservationDateTime.Value.Month, reservationDateTime.Value.Day,
                reservationHourTime.CurrDateTime.Hour, reservationHourTime.CurrDateTime.Minute, 1);
            reservationInfo.RMEMO = memRMemo.Text;
            reservationInfo.RSTATE = DBEntityReservation.ENUM_RSTATE.ChineseStrToEnumStr(cbxRState.SelectedItem.ToString());
            if (reservationInfo.RSTATE.Equals(DBEntityReservation.ENUM_RSTATE.C0A))
            {
                if (!checkReservationOver(dtReservationServiceItem, out error))
                {
                    MsgBox.MsgInfo(error);
                    return;
                }
            }
            if (!BussinessProxyManager.Instance.AdjustReservation(reservationInfo, employee, out error))
            {
                MsgBox.MsgInfo("保存预约记录失败：" + error);
                return;
            }
            
            MsgBox.MsgInfo("保存成功！");
            this.DialogResult = DialogResult.OK;
        }

        /// <summary>
        /// 检查当前项目是否完全预约
        /// </summary>
        /// <param name="drReservationServiceItem"></param>
        /// <param name="error"></param>
        /// <returns></returns>
        private bool checkReservationOver(DataTable dtReservationServiceItem, out string error)
        {
            error = string.Empty;
            DataRow[] drReservationDetail = dtReservationServiceItem.Select("", "", DataViewRowState.CurrentRows);
            foreach (DataRow dr in drReservationDetail)
            {
                if (!(dr[DBEntityReservationServiceItem.FieldName.RESERVATIONSTATE].ToString() == DBEntityReservationServiceItem.ENUM_RESERVATIONSTATE.C0A))
                {
                    error = "服务项目： [" + dr[DBEntityServiceItem.FieldName.SERVICEITEMCODE] + "]" + dr[DBEntityServiceItem.FieldName.SNAME].ToString() + " 还没有预约完成，请预约完成后在进行保存。";
                    return false;
                }
            }
            return true;
        }
        private void buttonX2_Click(object sender, EventArgs e)
        {
            if (isDialogResult)
            {
                this.DialogResult = DialogResult.OK; 
            }
            else
            {
                this.Close();
            }
        }
    }
}
